import cv2
import os
import numpy as np
import PIL.Image as Image
import pickle
import matplotlib.pyplot as plt
from sklearn.svm import LinearSVC
from sklearn.metrics import roc_curve, auc

def takeThird(item):
    return item[2]

def getHoGsAndLabels(svm, hog, ImagesPath, resultPath):
    Images = os.listdir(ImagesPath)
    for image in Images:
        img_norm = cv2.imread(ImagesPath + "\\" + image, cv2.IMREAD_COLOR)
        imgShape = img_norm.shape
        print(imgShape)
        tmpShape = np.array([imgShape[0], imgShape[1]])
        tmpImage = np.array(img_norm)
        posCoordinates = []
        while tmpShape[0] > 128 and tmpShape[1] > 64:
            # print(tmpImage.shape)
            # print(tmpShape)
            for h in range(0, tmpShape[0] - 129, 8):
                for w in range(0, tmpShape[1] - 65, 8):
                    
                    dataList = []

                    winStride = (8, 8)
                    padding = (0, 0)
                    hogValues = hog.compute(tmpImage[h:h+128, w:w+64], winStride, padding)
                    dataList.append(list(hogValues))
                    nparrData = np.array(dataList).reshape(-1, 3780)
                    pred = svm.predict(nparrData)[0]
                    if pred == 1:
                        confidence = svm.decision_function(nparrData)[0]
                        # print((h, w, confidence, tmpShape))
                        posCoordinates.append((h, w, confidence, (tmpShape[0], tmpShape[1])))
            tmpShape[0] = int(tmpShape[0] // 1.2)
            tmpShape[1] = int(tmpShape[1] // 1.2)
            tmpImage = cv2.resize(tmpImage, (tmpShape[1], tmpShape[0]))
            

        # posCoordinates.sort(key = takeThird, reverse = True)
        # print(posCoordinates[0])
        maxp = 0.0
        
        for item in posCoordinates:
            if item[2] > maxp:
                maxp = item[2]
                best = item

        x, y, confidence, shape = best
        print(best)
        tmpImage2 = cv2.resize(img_norm, (shape[1], shape[0]))
        for i in range(64):
            # print(x)
            # print(y)
            tmpImage2[x][y + i] = (0, 0, 255)
            tmpImage2[x + 127][y + i] = (0, 0, 255)
        for i in range(128):
            tmpImage2[x + i][y] = (0, 0, 255)
            tmpImage2[x + i][y + 63] = (0, 0, 255)
        tmpImage2 = cv2.resize(tmpImage2, (imgShape[1], imgShape[0]))
        cv2.imwrite(resultPath + "\\" + image, tmpImage2)

    
imageFolder = ".\\INRIAPerson\\Test\\posNew"
resultsFolder = ".\\INRIAPerson\\Test\\detect"
f = open('svm.model','rb')
s = f.read()
svm = pickle.loads(s)
f.close()

winSize = (64,128)
blockSize = (16,16)    
blockStride = (8,8)
cellSize = (8,8)
nbins = 9    
hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins) 
getHoGsAndLabels(svm, hog, imageFolder, resultsFolder)